package scatter.wwd.rest.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.LoginUser;
import scatter.common.dict.PublicDictEnums;
import scatter.common.rest.controller.SuperController;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.security.LoginUserTool;
import scatter.dict.rest.service.IDictService;
import scatter.file.rest.tool.FileNeedDeleteTool;
import scatter.wwd.pojo.form.app.GenerateCardForm;
import scatter.wwd.pojo.form.app.UserAlbumForm;
import scatter.wwd.pojo.form.app.UserTagForm;
import scatter.wwd.pojo.param.GenerateCardParam;
import scatter.wwd.pojo.po.ActivityParticipate;
import scatter.wwd.pojo.po.UserAlbum;
import scatter.wwd.pojo.po.UserCard;
import scatter.wwd.pojo.po.UserInfo;
import scatter.wwd.pojo.vo.*;
import scatter.wwd.rest.WwdConfiguration;
import scatter.wwd.rest.mapstruct.ActivityParticipateMapStruct;
import scatter.wwd.rest.mapstruct.UserAlbumMapStruct;
import scatter.wwd.rest.mapstruct.UserCardMapStruct;
import scatter.wwd.rest.service.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Date 6/12/21 11:51 AM
 * @Created by ciaj.
 */
@Slf4j
@Api(tags = "APP相关接口")
@RestController
@RequestMapping(WwdConfiguration.CONTROLLER_BASE_PATH + "/app")
public class MiniAppController extends SuperController {

    @Autowired
    private IMiniAppService iMiniAppService;

    @Autowired
    private IActivityParticipateService iActivityParticipateService;

    @Autowired
    private IUserTagService iUserTagService;

    @Autowired
    private IUserCardService iUserCardService;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IUserAlbumService iUserAlbumService;

    @Autowired
    private IDictService iDictService;


    @ApiOperation("APP用户标签编辑")
    @PostMapping("/user-tag-edit")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.CREATED)
    public void userTagEdit(@RequestBody @Valid UserTagForm form) {
        form.setUserId(LoginUserTool.getLoginUserId());
        iUserTagService.userTagEdit(form);
    }


    @ApiOperation("APP用户设置显示到首页")
    @PutMapping("/user-showInList")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.CREATED)
    public void showInList( Boolean showInList) {
        UserInfo u = new UserInfo();
        u.setIsShowInList(showInList);
        iUserInfoService.update(u, Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserId, LoginUserTool.getLoginUserId()));
    }


    @ApiOperation("APP获取用户相册")
    @GetMapping("/user-album/getList")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.OK)
    public UserInfoAlbumVo getUserAlbum() {
        String userId = LoginUserTool.getLoginUserId();
        //
        List<UserAlbum> userAlbumVos = iUserAlbumService.getByUserId(userId);
        List<UserAlbumVo> normal = UserAlbumMapStruct.INSTANCE.posToVos(userAlbumVos);
        if(CollUtil.isNotEmpty(normal)){
            normal.forEach(item->item.setType(UserAlbumVo.AlbumType.normal.name()));
        }
        UserInfoAlbumVo albumVo = new UserInfoAlbumVo();
        albumVo.setNormal(normal);
        //
        UserInfo userInfo = iUserInfoService.getByUserId(userId);
        if (!isStrEmpty(userInfo.getPicUrl())) {
            UserAlbumVo main = new UserAlbumVo();
            main.setType(UserAlbumVo.AlbumType.main.name());
            main.setId(userId);
            main.setUserId(userId);
            main.setPicUrl(userInfo.getPicUrl());
            main.setPicThumbUrl(main.getPicUrl());
            albumVo.setMain(Arrays.asList(main));
        }

        return albumVo;
    }

    @ApiOperation("APP用户相册删除")
    @DeleteMapping("/user-album/{type}/{id}")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delUserAlbum(@PathVariable("type") String type,@PathVariable("id") String id) {
        switch (UserAlbumVo.AlbumType.valueOf(type)){
            case main:
                UserInfo userInfo = iUserInfoService.getByUserId(LoginUserTool.getLoginUserId());
                FileNeedDeleteTool.addAsync(userInfo.getPicUrl(),"用户删除主图");
                iUserInfoService.update(Wrappers.<UserInfo>lambdaUpdate().set(UserInfo::getPicUrl, null).eq(UserInfo::getUserId, LoginUserTool.getLoginUserId()));
                break;
            case normal:
                UserAlbum byId = iUserAlbumService.getById(id);
                FileNeedDeleteTool.addAsync(byId.getPicUrl(),"用户删除相册副图");

                iUserAlbumService.removeById(id);
                break;
        }
    }

    @ApiOperation("APP用户卡片生成")
    @PostMapping("/user-gen-card")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.CREATED)
    public UserCardVo generateCard(@RequestBody GenerateCardForm form) {
        GenerateCardParam generateCardParam = new GenerateCardParam();
        String loginUserId = LoginUserTool.getLoginUserId();
        generateCardParam.setUserId(loginUserId);
        generateCardParam.setAppCode(form.getAppCode());
        List<UserAlbum> byUserId = iUserAlbumService.getByUserId(loginUserId);

        if (!isStrEmpty(form.getMainPicSelectedId())) {
            UserAlbum userAlbum = byUserId.stream().filter(item -> isEqual(item.getId(), form.getMainPicSelectedId())).findFirst().orElse(null);
            if (userAlbum != null) {
                generateCardParam.setMainPicUrl(userAlbum.getPicUrl());
            }
        }
        if (!isEmpty(form.getNormalPicSelectedIds())) {
            List<String> otherPicUrls = byUserId.stream().filter(item -> form.getNormalPicSelectedIds().contains(item.getId())).map(UserAlbum::getPicUrl).collect(Collectors.toList());
            generateCardParam.setOtherPicUrls(otherPicUrls);

        }

        iUserCardService.generateCard(generateCardParam);
        UserCard one = iUserCardService.getOne(Wrappers.<UserCard>lambdaQuery().eq(UserCard::getUserId, loginUserId), false);
        return UserCardMapStruct.INSTANCE.poToVo(one);
    }

    @ApiOperation("APP更新用户相册")
    @PutMapping("/user-album/update")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @ResponseStatus(HttpStatus.CREATED)
    public void updateUserAlbum(@RequestBody @Valid UserAlbumForm form,@ApiIgnore LoginUser user) {
        switch (UserAlbumVo.AlbumType.valueOf(form.getType())){
            case main:
                UserInfo userInfo = iUserInfoService.getByUserId(user.getId());
                FileNeedDeleteTool.addAsync(userInfo.getPicUrl(),"用户更新主图，原来图片需要删除");
                userInfo.setPicUrl(form.getUrl());
                iUserInfoService.updateById(userInfo);
                break;
            case normal:
                UserAlbum album = new UserAlbum()
                        .setUserId(user.getId())
                        .setPicThumbUrl(form.getUrl())
                        .setPicUrl(form.getUrl())
                        .setSeq(form.getSeq());
                iUserAlbumService.save(album);
                break;
        }
    }



    /**
     * 查询某个活动已报名数据，目前好像没有用到
     * @param id
     * @return
     */
    @ApiOperation("APP查询活动参与")
    @GetMapping("/activity-participate/{id}")
    @ResponseStatus(HttpStatus.OK)
    public List<ActivityParticipateVo> getActivityParticipateById(@PathVariable("id") String id) {

        List<ActivityParticipate> byActivityIdAndIsQuit = iActivityParticipateService.getByActivityIdAndIsQuit(id, false);
       List<ActivityParticipateVo> result =  ActivityParticipateMapStruct.INSTANCE.posToVos(byActivityIdAndIsQuit);
       fillGenderDictId(result);
        return result;
    }

    /**
     * 填充性别字典id，主要在h5展示已参与人员分开性别展示
     * @param result
     */
    private void fillGenderDictId(List<ActivityParticipateVo> result){
        if (CollectionUtil.isEmpty(result)) {
            return;
        }
        List<String> userIds = result.stream().map(ActivityParticipateVo::getUserId).collect(Collectors.toList());
        List<UserInfo> userInfos = iUserInfoService.getByUserIds(userIds);
        Map<String, String> userIdAndGenderIdMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getUserId, UserInfo::getGenderDictId));

        result.stream().forEach(item -> item.setUserGenderDictId(userIdAndGenderIdMap.get(item.getUserId())));

    }

    /**
     * 目前h5支付汇总确认使用
     * @param id
     * @param genderDictId
     * @return
     */
    @ApiOperation("APP查询活动支付详情")
    @PreAuthorize("hasAnyAuthority('appclient')")
    @GetMapping("/activity-pay/{id}")
    @ResponseStatus(HttpStatus.OK)
    public AppActivityPayDetailVo getActivityPayById(@PathVariable("id") String id,String genderDictId) {
        if (StrUtil.isEmpty(genderDictId)) {
            throw new BusinessException("性别不能为空");
        }
        String valueById = iDictService.getValueById(genderDictId);
        AppActivityPayDetailVo result = iMiniAppService.getActivityPayDetailById(id, PublicDictEnums.DictGender.valueOf(valueById));
        return result;
    }

}
